package cn.itsource.basic.config;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.BusinessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class AdviceController {


    @ResponseBody
    @ExceptionHandler
    public AjaxResult processException(Exception ex) {

        AjaxResult result;
//        if (ex instanceof ApiException) {
//            ApiException error = (ApiException) ex;
//            result= AjaxResult.me().fail(error.getMessage());
//        }else
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            result = AjaxResult.me().fail(exception.getBindingResult().getFieldError().getDefaultMessage());
        }
        else if (ex instanceof BusinessException) {
            BusinessException bex = (BusinessException) ex;
            result = AjaxResult.me().fail(bex.getMessage());
        }
        else {
            ex.printStackTrace();
            result = AjaxResult.me().fail();
        }
        return result;

    }
}